<?php

namespace App\Http\Controllers\Web;
use App\Http\Controllers\Controller;
use App\Repositories\PayRepository;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Yansongda\Pay\Pay;
use App\Models\WeixinUser;
use App\Tools\WechatPay;
use App\Models\Order;

class PayController extends Controller{

    protected $pay;
    /**
     * PayController constructor.
     * @param $AddressRepository
     */
    public function __construct(PayRepository $pay,Request $request){
        $this->pay = $pay;
    }

    //支付页面
    public function index()
    {
        return view('web.payment', ['title' => '支付']);
    }

    //微信h5页面
    public function h5(Request $request){
        $openid = new WechatPay();
        $openid->Getcode();
        return view('pay.wechatapp');
    }
    //微信h5支付页面
    public function payh5(Request $request){
            $rules = [
                'order_id'=>'required|exists:orders,id',
                'pay_way'=>'required',
                'code'=>'required'
            ];
            $message = [
                'order_id.*' =>'订单不存在',
                'pay_way.*'=>'请选择支付方式',
                'code.*'=>'无效code'
            ];
            $validator = Validator::make($request->all(), $rules,$message);
            //支付的订单
            if ($validator->fails()) {
                return show(201,$validator->errors()->first());
            }
            //支付的方式
            if($request->pay_way!='wechatapp'){
                return show(201,"支付方式不存在");
            }
            $order = Order::find($request->order_id);
            switch ($order->order_type)
            {
                case 0://外卖
                case 2://排队
                case 3://扫码
                case 4://直接付款
                case 5://充值
                    if($order->order_status!=1){
                        return show(201,"该订单状态不可支付");
                    }
                    //订单价格处理
                    $pay_order = [
                        'out_trade_no' => $order->order_number.'_'.$order->id,
                        'body' => '掌里通订单支付',
                        'total_fee' => 100*$order->order_amount,
                    ];
                    break;
                case 6://优惠卡
                    if($order->order_status!=1){
                        return show(201,"该订单状态不可支付");
                    }
                    $money = false;
                    $sharecard = config('Text')['shareCards'];
                    foreach($sharecard as $v){
                        if($v['money']==$order->amount){
                            $money = true;
                        }
                    }
                    if(!$money){
                        return show(90010,'该订单不可支付');
                    }
                    //订单价格处理
                    $pay_order = [
                        'out_trade_no' => $order->order_number.'_'.$order->id,
                        'body' => '掌里通订单支付',
                        'total_fee' => 100*$order->order_amount,
                    ];
                    break;
                case 1://预定
                    if($order->order_status==1){
                        //订单价格处理
                        $pay_order = [
                            'out_trade_no' => $this->order->order_number.'-1'.'_'.$this->order->id,
                            'body' => '掌里通订单支付',
                            'total_fee' => 100*$this->order->order_amount,
                        ];
                    }else if($this->order_status==3){
                        //订单价格处理
                        $pay_order = [
                            'out_trade_no' => $this->order->order_number.'-2'.'_'.$this->order->id,
                            'body' => '掌里通订单支付',
                            'total_fee' => 100*($this->order->order_price-$this->order->order_amount),
                        ];
                    }else{
                        return show(201,"该订单状态不可支付");
                    }
                    break;
                default://错误
                    return show(201,"该订单状态不可支付");
                    break;
            }
            try{
                $openid = new WechatPay();
                $pay_order['openid']=$openid->GetOpenid($request->code);//'oRZv9tk0dsAYLAsXRGncfu1naH-0';
                //return $pay_order;
                $result=Pay::wechat(config('pay')['wechat'])->mp($pay_order);
                return show(200,'获取数据成功',$result);
            }catch (\Exception $e){
//                dd($e->getLine().'                '.$e->getMessage());
                return show('201','支付失败，请重试或联系客服');
            }
    }

    public function payOrder(Request $request)
    {
        try{
            //订单号，支付方式(zhanglitong,wechat,alipay)，端口（web,miniapp,app,wechatapp）,支付密码
            if($request->pay_port=="wechatapp"){//需要传openid
                $wechatappuser =  WeixinUser::where('user_id',Auth::id())->first();
                if(!$wechatappuser){
                    return show('201','用户未授权登录');
                }else{
                    if($wechatappuser->openid==null){
                        return show('201','用户未授权登录');
                    }else{
                        $openid = $wechatappuser->openid;
                    }
                }
                //获取OPENID
                return $this->pay->payOrder($request->pay_way,$request->order_id,$request->pay_port,$request->payword,$openid);
            }else if($request->pay_port=="miniapp"){

                $request->token= $request->payword;
                if(!$request->token){
                    return show(201,'请用token换取支付信息');
                }else{
                    $miniappuser =  WeixinUser::where('token',$request->token)->first();
                    if(!$miniappuser){
                        return show('201','无效token');
                    }
                }
                return $this->pay->payOrder($request->pay_way,$request->order_id,$request->pay_port,$request->payword,$miniappuser->openid_mini);
            }else{
                return $this->pay->payOrder($request->pay_way,$request->order_id,$request->pay_port,$request->payword,'',$request->token);
            }
        }catch (\Exception $e){
//            dd($e->getMessage());
            return show('201','支付失败，请重试或联系客服');
        }

    }
    //微信异步回调
    public function wechat_notify()
    {
        $pay = Pay::wechat(config('pay')['wechat']);
         try{
            //验签
            $data = $pay->verify();
            $fromdata = $data->all();
            if($fromdata['result_code']=='SUCCESS' && $fromdata['return_code']=='SUCCESS'){
                //处理业务逻辑
                $out_trade_no=explode("_",$fromdata['out_trade_no']);
                return $this->pay->wechat_notify($out_trade_no[1],$pay->success());
            }

        }catch (\Exception $e) {
            // $e->getMessage();
        }
        Log::info("check error");
        return $pay->success();
    }


    //支付宝异步回调
    public function alipay_notify(Request $request)
    {

        $pay = Pay::alipay(config('pay')['alipay']);
        try{
            //验签
            $data = $pay->verify();
            $fromdata = $data->all();
            if($fromdata['trade_status']=='TRADE_SUCCESS'){
                //处理业务逻辑
                $out_trade_no=explode("_",$fromdata['out_trade_no']);
                return $this->pay->alipay_notify($out_trade_no[1],$pay->success());
            }

        }catch (\Exception $e) {
            //$e->getMessage();
        }
        Log::info("check error");
        return $pay->success();
    }
    //支付宝同步回调
    public function alipay_return(Request $request)
    {
        $pay = Pay::alipay(config('pay')['alipay']);
        try{
            //验签
            $data = $pay->verify();
            $fromdata = $data->all();
            if($fromdata['out_trade_no']) {
                $out_trade_no = explode("_", $fromdata['out_trade_no']);
                return redirect('/mobile/order-detail?id='.$out_trade_no[1]);
            }

        }catch (\Exception $e) {
            // $e->getMessage();
        }
        return redirect('/mobile/index');
    }



}